<?php
namespace App\Repositories;
use App\Model\Role as RoleModel;
use App\Model\User;
use App\Model\Access;
use App\Events\RoleStored;
use App\Events\RoleRemoved;
use Illuminate\Validation\ValidationException;
use collect;

class Role implements Repository
{
	/***
	保存角色
	***/
	public function store($data,$notify){
		
		$role_data['name']= $data['name'];
		
		isset($data['desc'])?$role_data['desc']= $data['desc']:'';
			
		if(isset($data['id'])){
			
			$role=RoleModel::where("id",$data['id'])->first();//验证规则已验证过一定会存在，否则进不来

			$role->update($role_data);
			
			$notify["method"]="edit";
			
		}else{
		
			$role=RoleModel::create($role_data);
			
			$notify["method"]="add";
		}
		
		if(isset($data["access"])){
			
			$access=Access::whereIn("id",$data["access"])->where("parent_id",">",0)->distinct()->get(["parent_id"]);

			$access=array_merge(collect($access->toArray())->flatten()->toArray(),$data["access"]);
			
			$role->access()->sync($access);
		}
		
		event(new RoleStored($role,$notify));
		
		return true ;
	}
	
	/*删除角色*/
	public function remove($id,$notify)
	{
		if(!$roles=RoleModel::whereIn("id",$id)->where('is_system','<>',1)->get()){
			return true;
		}
		
		$data=[];
			
		foreach($roles as $item){ 
		
			array_push($data,$item->id);
			
			$item->access()->detach();//删除角色关联权限

		}

		RoleModel::whereIn("id",$id)->where('is_system','<>',1)->delete();
		
		User::whereIn('role_id',$data)->update(['role_id'=>0]);
		
		$notify["method"]="remove";

		event(new RoleRemoved($roles,$notify));
		  
		return true;
	}
}
